<?
define ('DBPATH', './pimpDb');    

 
function putf($path, $str)
{
    $fp=fopen($path,'w');
    fwrite ($fp,$str);
    fclose($fp); 
}   

function page_load()   
{                
    $arguments = array();          
    $action    = "";          
    $resultxml = "";                
              
    if (count($_FILES)>0)  // read uploaded files and add them to the user's config file
    {
        foreach( $_FILES as $file_name => $file_array ) 
        {  
            $upload_path = $file_array['tmp_name'];
            $upload_name = $file_array['name'];
            $upload_type = $file_array['type'];
            $upload_size = $file_array['size'];  
          
            $data = fread(fopen($upload_path, "r"), filesize($upload_path));

            $url = "images/$upload_name";
            putf ($url, $data);
            echo AddPicture ($upload_name,$url);

        } 
        exit;
    } // end upload file handler  


    if (isset($_GET['v'])) render_working_data($_GET['v']);
                                                            
    if (isset($HTTP_RAW_POST_DATA)) {                                                                           
        $input = $HTTP_RAW_POST_DATA;                                                                           
    } else if (strlen($HTTP_POST_VARS["input"])>0) {                                                                           
        $input = stripslashes($HTTP_POST_VARS["input"]);                                                                           
    } else {                                                                           
        $input = implode("\r\n", file('php://input'));                                                                           
    }                          


    if ($dom=domxml_open_mem($input))                                                                         
    {                                                                                                   
        foreach ($dom->get_elements_by_tagname("Body") as $body)                                                                      
        {                                                              
            foreach ($body->child_nodes() as $x)                                                                      
            {                                                                          
                $action=$x->node_name();                                   
                foreach ($x->child_nodes() as $arg)                                                                      
                {                                                
                    $arguments[$arg->node_name()]=$arg->get_content();                                               
                }                                               
            }                     
        }                    
    }                    
            

    if ($action=="GetPictures")                                       
    {                                                    
        $result=''; # initialize function return value here                                    
        $results=GetPictures(); # create result from array                                      
        foreach ($results as $tmp)                                                              
        {                                                             
            $result.='<' . $action . 'Result>' . $tmp->serialize(); 
            $result.='</' . $action . 'Result>';                                                            
        }   
        $resultxml= '<' . $action . 'Response xmlns="http://www.cyber8.net/webservices/pimp">' . $result . '</' . $action . 'Response>';                                       
    }  
     

    if ($action=="GetPicture")                                       
    {                                                    
        $result=''; # initialize function return value here
        $result.='<' . $action . 'Result>';
         
        $oPPicture = GetPicture($arguments['id']);
        $result.=$oPPicture->serialize();        
            
        $result.='</' . $action . 'Result>';  
        $resultxml= '<' . $action . 'Response xmlns="http://www.cyber8.net/webservices/pimp">' . $result . '</' . $action . 'Response>';                                       
    }  
     
     if ($action=="DeletePicture")                                       
    {                                                    
        $result=''; # initialize function return value here
        $result.='<' . $action . 'Result>';
        
        $result.=DeletePicture($arguments['id']);
            
        $result.='</' . $action . 'Result>';  
        $resultxml= '<' . $action . 'Response xmlns="http://www.cyber8.net/webservices/pimp">' . $result . '</' . $action . 'Response>';                                       
    }  
     
    if ($action=="ApplyTool")                                       
    {                                                    
        $result=''; # initialize function return value here
        $result.='<' . $action . 'Result>';
        
        $result.=ApplyTool($arguments['id'], $arguments['tool'], $arguments['brush'], $arguments['color'], $arguments['coords']);
            
        $result.='</' . $action . 'Result>';  
        $resultxml= '<' . $action . 'Response xmlns="http://www.cyber8.net/webservices/pimp">' . $result . '</' . $action . 'Response>';                                       
    }  
     
     if ($action=="ResetImage")                                       
    {                                                    
        $result=''; # initialize function return value here
        $result.='<' . $action . 'Result>';
        
        $result.=ResetImage($arguments['id']);
            
        $result.='</' . $action . 'Result>';  
        $resultxml= '<' . $action . 'Response xmlns="http://www.cyber8.net/webservices/pimp">' . $result . '</' . $action . 'Response>';                                       
    }  
     
    if ($action=="GetPixelAt")                                       
    {                                                    
        $result=''; # initialize function return value here
        $result.='<' . $action . 'Result>';
        
        $result.=GetPixelAt($arguments['id'], $arguments['x'], $arguments['y']);
            
        $result.='</' . $action . 'Result>';  
        $resultxml= '<' . $action . 'Response xmlns="http://www.cyber8.net/webservices/pimp">' . $result . '</' . $action . 'Response>';                                       
    }  
     
 

    if ($action=="GetPictureLog")                                       
    {                                                    
        $result=''; # initialize function return value here                                    
        $results=GetPictureLog($arguments['id']); # create result from array                                      
        foreach ($results as $tmp)                                                              
        {                                                             
            $result.='<' . $action . 'Result>' . $tmp->serialize(); 
            $result.='</' . $action . 'Result>';                                                            
        }   
        $resultxml= '<' . $action . 'Response xmlns="http://www.cyber8.net/webservices/pimp">' . $result . '</' . $action . 'Response>';                                       
    }  
     
 
    if ($action=="ApplyPictureLog")                                       
    {                                                    
        $result=''; # initialize function return value here
        $result.='<' . $action . 'Result>';
        
        $result.=ApplyPictureLog($arguments['id'], $arguments['step']);
            
        $result.='</' . $action . 'Result>';  
        $resultxml= '<' . $action . 'Response xmlns="http://www.cyber8.net/webservices/pimp">' . $result . '</' . $action . 'Response>';                                       
    }  
     



    if ($resultxml!="")                                         
    {                                               
        header ("Content-Type: text/xml");                                                                         
        $output = '<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">                                                                      
                   <soap:Body>' . $resultxml . '</soap:Body></soap:Envelope>';                                                                
        echo $output;                        
        exit;                                                                          
    }                                    
    echo $input;                           
    exit;     
}             
          
page_load();  
  
class ToolInfo
{
    var $name;
    var $brush;
    var $color;
    var $coords;
    function ToolInfo($row=NULL)
    {
        if ($row)
        {
            $this->name=$row['name'];
            $this->brush=$row['brush'];
            $this->color=$row['color'];
            $this->coords=$row['coords'];
        }
    }
        
    function serialize()
    { 
        $output="";
        $output.="<name><![CDATA[" . $this->name . "]]></name>";
        $output.="<brush><![CDATA[" . $this->brush . "]]></brush>";
        $output.="<color><![CDATA[" . $this->color . "]]></color>";
        $output.="<coords><![CDATA[" . $this->coords . "]]></coords>"; 
        return $output;        
    }    
}


class PPicture
{
    var $name;
    var $url;
    var $size;
    var $id;
    function PPicture($row=NULL)
    {
        if ($row)
        {
            $this->name=$row['name'];
            $this->url=$row['url'];
            $this->size=$row['size'];
            $this->id=$row['id'];
        }
    }
        
    function serialize()
    { 
        $output="";
        $output.="<name><![CDATA[" . $this->name . "]]></name>";
        $output.="<url><![CDATA[" . $this->url . "]]></url>";
        $output.="<size><![CDATA[" . $this->size . "]]></size>";
        $output.="<id><![CDATA[" . $this->id . "]]></id>"; 
        return $output;        
    }    
}


function AddPicture($name, $url)
{
    $im = imagecreatefromjpeg ($url);
    $sx = imagesx ($im);
    $sy = imagesy ($im);
    $id = uuid();
    $db = GetDb ();
    
    $root = select_single_node ($db, '//pimp');
    $node = $db->create_element('ppicture'); 
    $node->set_attribute("name", $name); 
    $node->set_attribute("url", $url); 
    $node->set_attribute("size", "$sx $sy"); 
    $node->set_attribute("id", $id); 
    $root->append_child($node); 


    SaveDb($db);

    return $id;

}

function render_working_data ($id)
{
    //header ('Content-Type; image/jpeg');
    if (strpos ($id,'/')!==false)
    {
        $tmp=explode ('/', $id);
        $id=$tmp[0];
    }

    if ($id=='marquee')
    {
        $id  = $tmp[1];
        $src_x  = $tmp[2];
        $src_y  = $tmp[3];
        $x2  = $tmp[4];
        $y2  = $tmp[5]; 
        $dst_w = $x2-$src_x;
        $dst_h = $y2-$src_y;

 

        $db = GetDb ();    
        $im = select_single_node ($db, "//pimp/ppicture[@id='$id']");
        $url = $im->get_attribute ('url');

        $loc = GetIm($id);
        if (file_exists ($loc)) 
            $src_image = imagecreatefrompng ($loc);
        else
        {
            $src_image=imagecreatefromjpeg ($url); 
        }
         
        $src_h=imagesy($src_image);
        $src_w=imagesx($src_image);

        $dst_image=imagecreatetruecolor ($dst_w,$dst_h);

        $bk  = imagecolorallocate ($dst_image,255,0,255); 
        imagecolortransparent ($dst_image, $bk);
        imagefill ($dst_image,0,0,$bk);

      imagecopyresized  ( $dst_image  , $src_image  , 0  , 0  , $src_x  , $src_y  , $dst_w  , $dst_h  , $dst_w  , $dst_h  );

 

        imagepng ($dst_image);
        imagedestroy ($dst_image);
        imagedestroy ($src_image);
        exit;
    }

    if ($id=='backgrid')
    {
        $sz  = $tmp[1];
        $im  = imagecreate ($sz*2,$sz*2);
        $wht = imagecolorallocate ($im,255,255,255);
        $blk = imagecolorallocate ($im,150,150,150); 
        imagefilledrectangle ($im, 0,0,$sz,$sz,$blk);
        imagefilledrectangle ($im, $sz,$sz, $sz*2,$sz*2,$blk);
        imagejpeg ($im);
        imagedestroy ($im);
        exit;
    }

    if ($id=='mkbrush')
    {
        $sz  = $tmp[1];
        $bsh = $tmp[2];
        $hlo = $tmp[3];
        $rgb = html2rgb($bsh);
        $im  = imagecreatetruecolor ($sz,$sz);
        $bk  = imagecolorallocate ($im,255,0,255);
        $hue = imagecolorallocate ($im,$rgb[0],$rgb[1],$rgb[2]);
        imagecolortransparent ($im, $bk);
        imagefill ($im,0,0,$bk);
        if ($hlo=='hollow') imageellipse ($im, $sz/2, $sz/2, $sz, $sz, $hue);
        else imagefilledellipse ($im, $sz/2, $sz/2, $sz, $sz, $hue);
        imagepng ($im);
        imagedestroy ($im);
        exit;
    }

    if ($id=='brushlist')
    {
        $x   = 0;
        $sp  = array ('20'=>'50',
                      '22'=>'60',
                      '24'=>'70',
                      '26'=>'80',
                      '32'=>'100' 
                      );
        $bsh = $tmp[1];
        $f   = imagefontwidth(1);
        $im  = imagecreate (200,90);
        $wht = imagecolorallocate ($im,255,255,255);
        $ylo = imagecolorallocate ($im,255,255,0);
        $hue = imagecolorallocate ($im,100,100,100);
        for ($e=1;$e<=16;$e*=2)
        {
            $x += 30;
            if ($e==$bsh)
                imagefilledrectangle  ( $im  , $x-15  ,0  , $x+15  , 45  , $ylo  );
            imageellipse ($im, $x, 20, $e, $e, $hue);
            imagestring  ( $im  , 1  ,  $x - ( ($f * strlen($e)) / 2) , 30  ,$e  , $hue  );
      
        }
        $x   = 0;
        while (list($e,$v)=each($sp))
        {
            $x += 30;
            if ($v==$bsh)
                imagefilledrectangle  ( $im  , $x-15  ,45  , $x+15  , 90  , $ylo  );
            imageellipse ($im, $x, 55, $e, $e, $hue);
            imagestring  ( $im  , 1  ,  $x - ( ($f * strlen($e)) / 2) , 70  ,$v  , $hue  ); 

        }
        imagejpeg ($im);
        imagedestroy ($im);
        exit;
    }

    $db = GetDb ();    
    $im = select_single_node ($db, "//pimp/ppicture[@id='$id']");
    $url = $im->get_attribute ('url');

    $loc = GetIm($id);
    if (file_exists ($loc)) 
        $pic = imagecreatefrompng ($loc);
    else
    {
        $pic=imagecreatefromjpeg ($url);
        imagepng ($pic,$loc);
    }
    imagepng ($pic);

    $loc2 = "cache/$id.history.png";
    if (!file_exists ($loc2))  
        imagepng (CreateHistoryPic($pic),$loc2);

    imagedestroy ($pic);

    exit;
}

function ResetImage ($id)
{
    $db = GetDb ();    
    $im = select_single_node ($db, "//pimp/ppicture[@id='$id']");
    $url = $im->get_attribute ('url');

    $loc = GetIm($id);
    if (file_exists ($loc)) 
        unlink ($loc);
    ClearLogDb ($id);
    return file_exists ($loc);
}

function LogTool ($id, $tool, $brush, $color, $coords)
{
    $db = GetLogDb($id);
    $top = select_single_node ($db, "//log");


    $node = $db->create_element('entry'); 
    $node->set_attribute("tool", $tool); 
    $node->set_attribute("brush", $brush); 
    $node->set_attribute("color", "$color"); 
    $node->set_attribute("coords", $coords); 

    
    $top->append_child($node); 

    SaveLogDb ($id, $db);
}

function ApplyPictureLog ($id, $step)
{
    $db  = GetDb ();    
    $im  = select_single_node ($db, "//pimp/ppicture[@id='$id']");
    $url = $im->get_attribute ('url');
    $pic = imagecreatefromjpeg ($url);

    $db = GetLogDb($id);
    $top = select_nodes ($db, "//entry");
    for ($r=0;$r<sizeof ($top) && $r<=$step;$r++)
    {
        $ret=CreateToolInfoRow ($top[$r]);
        $pic = _ApplyTool ($pic, $ret->name, $ret->brush, $ret->color, $ret->coords);
    }
    $loc = "cache/$id.history.png";
    imagepng (CreateHistoryPic($pic),$loc);
    return $ret;
}


function CreateHistoryPic ($src_image)
{
    $sz=160;
    $src_h=imagesy($src_image);
    $src_w=imagesx($src_image);
    $r=$src_w/$src_h;
    if ($src_w>$src_h) { $dst_w=$sz;$dst_h=$dst_w/$r; }
    else { $dst_h=$sz;$dst_w=$dst_h*$r; }
     $dst_image = imagecreatetruecolor ($dst_w,$dst_h);
    $hue = imagecolorallocate ($dst_image,255,0,255);
    imagecolortransparent ($dst_image, $hue);
    imagefill ($dst_image, 0,0,  $hue);
    imagecopyresized  ( $dst_image  , $src_image  , 0  , 0  , 0  , 0  , $dst_w  , $dst_h  , $src_w  , $src_h  );
    return $dst_image;
}


function ApplyTool ($id, $tool, $brush, $color, $coords, $input=NULL)
{
    $db = GetDb ();    
    $im = select_single_node ($db, "//pimp/ppicture[@id='$id']");
    $url = $im->get_attribute ('url');

    $loc = GetIm($id);
    if (file_exists ($loc)) 
    {
        $pic = imagecreatefrompng ($loc);
        $pic = _ApplyTool($pic, $tool, $brush, $color, $coords);
//         $rbg = $color==''? array(255,0,255) : html2rgb($color);
//         $hue = imagecolorallocate ($pic,$rbg[0],$rbg[1],$rbg[2]);
//         if ($tool=='Eraser') imagecolortransparent ($pic, $hue);
//         $dot = explode (' ', $coords);
//         for ($i=0;$i<sizeof($dot);$i++)
//         {
//             $dit = explode ('x', $dot[$i]);
//             imagefilledellipse  ( $pic  , $dit[0]  , $dit[1]  , $brush  , $brush  , $hue  );
//         }
    $loc2 = "cache/$id.history.png";
        imagepng ($pic,$loc);
        imagepng (CreateHistoryPic($pic),$loc2);
        LogTool ($id, $tool, $brush, $color, $coords);
        return $coords;
    }
    return 0;
  //  imagedestroy ($pic); 
}

function _ApplyTool($pic, $tool, $brush, $color, $coords)
{
      $rbg = $color==''? array(255,0,255) : html2rgb($color);
      $hue = imagecolorallocate ($pic,$rbg[0],$rbg[1],$rbg[2]);
      if ($tool=='Eraser') imagecolortransparent ($pic, $hue);
      $dot = explode (' ', $coords);
      if ($tool=="Bucket")
      {
          imagefill ($pic, $dot[0], $dot[1], $hue);
          return $pic;
      }
      for ($i=0;$i<sizeof($dot);$i++)
      {
          $dit = explode ('x', $dot[$i]);
          imagefilledellipse  ( $pic  , $dit[0]  , $dit[1]  , $brush  , $brush  , $hue  );
      }
      return $pic;
}

function html2rgb($color)
{
    if ($color[0] == '#')
        $color = substr($color, 1);

    if (strlen($color) == 6)
        list($r, $g, $b) = array($color[0].$color[1],
                                 $color[2].$color[3],
                                 $color[4].$color[5]);
    elseif (strlen($color) == 3)
        list($r, $g, $b) = array($color[0].$color[0], $color[1].$color[1], $color[2].$color[2]);
    else
        return false;

    $r = hexdec($r); $g = hexdec($g); $b = hexdec($b);

  
    return array($r, $g, $b);
}

function GetPixelAt($id, $x, $y)
{
    $db = GetDb ();    
    $im = select_single_node ($db, "//pimp/ppicture[@id='$id']");
    $url = $im->get_attribute ('url');

    $loc = GetIm($id);
    if (file_exists ($loc)) 
    {
        $pic = imagecreatefrompng ($loc); 
        $rgb = imagecolorat($pic, $x, $y);
        $r = ($rgb >> 16) & 0xFF;
        $g = ($rgb >> 8) & 0xFF;
        $b = $rgb & 0xFF;
        return padrgb ($r) . padrgb($g) . padrgb($b);
    }
    return 0;
}

function padrgb ($value)
{
    return strtoupper(str_pad(dechex($value), 2, 0, STR_PAD_LEFT));
}


function DeletePicture($id)
{
    $db = GetDb ();    
    $im = select_single_node ($db, "//pimp/ppicture[@id='$id']");
    $im->unlink_node ();
    SaveDb($db);
}

function GetPicture($id)
{
    $db = GetDb ();    
    $im = select_single_node ($db, "//pimp/ppicture[@id='$id']");
    return CreateRow ($im);
}

function GetPictures()
{
    $ret = array();
    $db = GetDb ();    
    $im = select_nodes ($db, "//pimp/ppicture");
    for ($r=0;$r<sizeof ($im);$r++)
        $ret[]=CreateRow ($im[$r]);
    return $ret;
}


function GetPictureLog ($id)
{
    $ret = array();
    $db = GetLogDb($id);
    $top = select_nodes ($db, "//entry");
    for ($r=0;$r<sizeof ($top);$r++)
        $ret[]=CreateToolInfoRow ($top[$r]);
    return $ret;
}

function CreateToolInfoRow ($element)
{
    return new ToolInfo(array ('name'=>$element->get_attribute('tool'),
                  'brush'=>$element->get_attribute('brush'),
                  'color'=>$element->get_attribute('color'),
                  'coords'=>$element->get_attribute('coords') 
                  ));
}

function CreateRow ($element)
{
    return new PPicture(array ('id'=>$element->get_attribute('id'),
                  'name'=>$element->get_attribute('name'),
                  'url'=>$element->get_attribute('url'),
                  'size'=>$element->get_attribute('size') 
                  ));
}

function SaveDb($dom)
{
    $dom->dump_file (DBPATH);
}

function GetIm($id)
{
    return "cache/$id.png";
}

function GetLogDb($id)
{
    $logpath = "cache/$id.log";                                                                                                 
    if (! ($dom = domxml_open_file( $logpath )))    
    {
        $dom = domxml_open_mem( '<log/>' );
    }
    return $dom;
}

function SaveLogDb ($id, $dom)
{
    $logpath = "cache/$id.log";   
    $dom->dump_file ($logpath);
}

function ClearLogDb ($id)
{
    $logpath = "cache/$id.log";   
    unlink ($logpath);
}

function GetDb()
{
                                                                                                                        
    if (! ($dom = domxml_open_file( DBPATH )))    
    {
        $dom = domxml_open_mem( '<pimp/>' );
    }
    return $dom;
}                                                                                                                                                                                                                                                                                                                                                                                          

function select_single_node($node, $value) // select_single_node                                                                                                                                                                                                                                                                                                                                                               
{                                                                                                                                                                                                                                                                                                                                                                  
    $xpath = xpath_new_context($node);                                                                                                                                                                                                                                                                                                                                                               
    $xnode = xpath_eval($xpath, $value);                                                                                                                                                                                                                                                                                                                                                                
    foreach ($xnode->nodeset as $node) return $node;                                                                                                                                                                                                                                                                                                                 
    return false;                                                                                                                                                                                                                                                                                                                                                                 
} // select_single_node                                                                                                                                                                                                                                                                                                                                                               

function select_nodes($node, $value) // select_nodes                                                                                                                                                                                                                                                                                                                                                               
{                                                                                                                                                                                                                                                                                                                                                                  
    $xpath = xpath_new_context($node);                                                                                                                                                                                                                                                                                                                                                               
    $xnode = xpath_eval($xpath, $value);                                                                                                                                                                                                                                                                                                                                                                 
    return $xnode->nodeset;                                                                                                                                                                                                                                                                                                                                                                 
} // select_nodes                                                                                                                                                                                                           
 
// 
/*
  * Generates an UUID
  * 
  * @author     Anis uddin Ahmad <admin@ajaxray.com>
  * @param      string  an optional prefix
  * @return     string  the formatted uuid
  */
  function uuid()
  {
    $chars = md5(uniqid(mt_rand(), true));
    $uuid  = substr($chars,0,8) . '-';
    $uuid .= substr($chars,8,4) . '-';
    $uuid .= substr($chars,12,4) . '-';
    $uuid .= substr($chars,16,4) . '-';
    $uuid .= substr($chars,20,12);
    return $uuid;
  }

    
?>
